package traveler.activities;

import traveler.controllers.CourseAddController;
import traveler.models.Step;
import traveler.tools.Tools;
import traveler.activities.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class CourseAddActivity extends Activity {

	
    public static final int DIALOG_PLUG_CHOOSER = 1;
    public static final int DIALOG_DELETE_ACTION = 2;

	public static final int BUTTON_STEPS = 1;
	public static final int BUTTON_COURSE = 2;

	private CourseAddController _controller = null;

	private RelativeLayout _steps = null;
	private RelativeLayout _course = null;
	private LinearLayout _add_step = null;
    private LinearLayout _list_steps = null;
	private Button _image = null;
	private EditText _ed_geo = null;
	private ViewFlipper _flipper = null;
	private GroupInterfaceListener gil = null;
	
    /** REQUEST_CODE pour l'ouverture de la galerie d'image */
    public static final int SELECT_PICTURE = 1;
    
    public static final int FAV_MAX_WIDTH = 150;
    public static final int FAV_MAX_HEIGHT = 150;
    
    /** String du chemin de l'image finale */
    private String finalImage;

	
	/** Animation gauche entrŽe */
    private Animation slideLeftIn = null;
    /** Animation gauche sortie */
    private Animation slideLeftOut = null;
    /** Animation droite entrŽe */
    private Animation slideRightIn = null;
    /** Animation gauche sortie */
    private Animation slideRightOut = null;

    /** Identifieur pour la distance minimum de gesture */
    private static final int SWIPE_MIN_DISTANCE = 120;
    /** Identifieur pour la distance maximum de gesture */
    private static final int SWIPE_MAX_OFF_PATH = 250;
    /** Identifieur pour la vitesse de gesture */
    private static final int SWIPE_THRESHOLD_VELOCITY = 150;

    /** GestureDetector */
    private GestureDetector gestureDetector = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_add);

		_controller = new CourseAddController(this);

		_steps = (RelativeLayout) findViewById(R.id.course_add_relative_manage_step);
		_steps.setId(BUTTON_STEPS);
		_steps.setOnClickListener(_controller);
		
		_course = (RelativeLayout) findViewById(R.id.course_add_relative_manage_course);
		_course.setOnClickListener(_controller);
		
		_add_step = (LinearLayout) findViewById(R.id.course_add_linear_add_step);
		_add_step.setOnClickListener(_controller);
		
		_image = (Button) findViewById(R.id.course_add_bt_img);
		_image.setOnClickListener(_controller);
		
		_ed_geo = (EditText)findViewById(R.id.course_add_step_ed_geo);
		
		

		_flipper = (ViewFlipper) this.findViewById(R.id.course_add_flipper);
		// this.flipper.setBackgroundColor(Color.RED);
		
		this._list_steps = (LinearLayout) this.findViewById(
                R.id.course_add_list_steps);
		
		this.gestureDetector = new GestureDetector(new MyGestureDetector(
				_flipper));
		
		this.gil = new GroupInterfaceListener(this.gestureDetector);

        this.slideLeftIn = AnimationUtils.loadAnimation(this,
                R.anim.slide_left_in);
        this.slideLeftIn.setDuration(300);
        this.slideLeftOut = AnimationUtils.loadAnimation(this,
                R.anim.slide_left_out);
        this.slideLeftOut.setDuration(300);
        this.slideRightIn = AnimationUtils.loadAnimation(this,
                R.anim.slide_right_in);
        this.slideRightIn.setDuration(300);
        this.slideRightOut = AnimationUtils.loadAnimation(this,
        		R.anim.slide_right_out);
        this.slideRightOut.setDuration(300);




	}
	
	public void onClickGeo(View v){
		_ed_geo = (EditText)findViewById(R.id.course_add_step_ed_geo);
//		_ed_geo.setText("blabla");
		_ed_geo.setHint("blabla");
		Log.e("error", "vas te faire");
	}
	
	public GroupInterfaceListener getGil() {
		return gil;
	}

	public void setGil(GroupInterfaceListener gil) {
		this.gil = gil;
	}

	/**
     * Permet de lancer l'animation et le changement de flipper
     * Envoie vers le flipper suivant
     */
    public void flipNext() {
        this._flipper.setInAnimation(this.slideLeftIn);
        this._flipper.setOutAnimation(this.slideLeftOut);
        this._flipper.showNext();
//        this.updateButtonsAndText();
    }

    /**
     * Permet de lancer l'animation et le changement de flipper
     * Envoie vers le flipper prŽcŽdent
     */
    public void flipPrevious() {
        this._flipper.setInAnimation(this.slideRightIn);
        this._flipper.setOutAnimation(this.slideRightOut);
        this._flipper.showPrevious();
//        this.updateButtonsAndText();
    }
    
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        Log.e("PI::onTouchEvent", "START/END");
//        return super.onTouchEvent(event);
//    }
    
    /**
     * RŽsultante de l'activity image Appelle la fonction getPath des
     * images/fichiers recherchŽs
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(resultCode) {
        case Activity.RESULT_OK:
            switch(requestCode) {
            case CourseAddActivity.SELECT_PICTURE:
                // on initialise finalImage = vide
                this.finalImage = "";
                
                Uri selectedImageUri = data.getData();
                Log.e("URI", "URI : "+selectedImageUri);

                // Depuis le gestionnaire de fichier si existant
                String filePath = selectedImageUri.getPath();
                Log.e("filePath", "URI : "+filePath);
                
                // Depuis la galerie
                String imagePath = this.getRealPathFromURI(selectedImageUri);
                Log.e("ImagePath", "URI : "+imagePath);
                
                ImageView jpgView = (ImageView) findViewById(
                        R.id.course_add_image);
                
                // On affiche le chemin dans le champs de texte
                if (imagePath != null) {
                    Log.e("imagePath", "URI : "+filePath);
                    this.finalImage = imagePath.toString();
                } else if (filePath != null){
                    //explorer
                    Log.e("filePath", "URI : "+filePath);
                    this.finalImage = filePath.toString(); 
                }
                
                Bitmap resizedBM = Tools.resizeImageForFavicon(
                        this.finalImage,
                        CourseAddActivity.FAV_MAX_WIDTH,
                        CourseAddActivity.FAV_MAX_HEIGHT
                );
                
                jpgView.setImageBitmap(resizedBM);
                
                break;
            }
            
            break;
        default:
            break;
        }
    }
    
    /**
     * RŽcup�re le chemin de l'image ou fichier
     * 
     * @param uri
     *            uri de l'image/fichier
     * @return String retourne le path
     */
    public String getRealPathFromURI(Uri uri) {
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = this.managedQuery(uri, projection, null, null, null);
        if (cursor == null) {
            return null;
        } else {
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
    }
    
    /**
     * Classe de gesture permettant de changer de groupe en glissant le doigt
     * sur l'Žcran
     *
     */
    class MyGestureDetector extends SimpleOnGestureListener {
        ViewFlipper vf;

        /**
         * Constructeur
         * @param vf
         */
        public MyGestureDetector(ViewFlipper vf) {
            this.vf = vf;
            Log.e("PlugActivity.MyGestureDetector::CONSTRUCTOR", "YES");
        }
        
        


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
             Log.e("PlugActivity.MyGestureDetector::onFling", "START");
            if (this.vf.getChildCount() > 1) {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                     Log.e("PlugActivity.MyGestureDetector::onFling", "END");
                    return false;
                } else {
                    boolean r = true;

                    // right to left swipe
                    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                        ((CourseAddActivity) this.vf.getContext()).flipNext();
                        // left to right swipe
                    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                        ((CourseAddActivity) this.vf.getContext()).flipPrevious();
                    } else {
                        r = false;
                    }

                     Log.e("PlugActivity.MyGestureDetector::onFling", "END");
                    return r;
                }
            } else {
                 Log.e("PlugActivity.MyGestureDetector::onFling", "END");
                return false;
            }
        }
    }
    
    /**
     * Class GroupInterfaceListener
     *
     */
    class GroupInterfaceListener implements View.OnTouchListener {
        private GestureDetector gd;

        /**
         * Constructeur
         * @param gd
         */
        public GroupInterfaceListener(GestureDetector gd) {
        	Log.e("GIL", "constructor");
            this.gd = gd;
        }

        public boolean onTouch(View v, MotionEvent event) {
        	Log.e("connard", "enculŽ");
            return this.gd.onTouchEvent(event);
        } 
    }
    
    public void addAction() {
        Log.d("SAA::addAction","START");
        
        StepInterface a = new StepInterface(this, new Step(this)); 

        this._list_steps.addView(a);
        

       
        Log.d("SAA::addAction","END");
    }
    
    public class StepInterface extends LinearLayout {
        /** Identificateur du bouton Supprimer */
        public static final int BUTTON_DELETE = 1;
        /**  Identificateur du clic sur le texte */
        public static final int ACTION_TEXT = 2;
        /** Identificateur du bouton clock */
        public static final int DELAY_CLOCK = 3;

        /** TextView Nom de la prise */
        private TextView plugName = null;
        /** TextView texte correspondant ˆ l'action */
        private TextView actionText;
        /** Bouton Supprimer */
        private Button delete = null;
        /** RelativeLayout Nom de la prise */
        private RelativeLayout plug = null;
        /**
         * Constructeur
         * @param parent
         * @param step
         */
        public StepInterface(CourseAddActivity parent, Step step) {
            super(parent);
            this.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            this.setOrientation(LinearLayout.VERTICAL);

            

            RelativeLayout.LayoutParams lp = null;
            this.plug = new RelativeLayout(parent);

            // Affichage du nom
            this.plugName = new TextView(parent);
            this.plugName.setTextColor(Color.BLACK);
            this.plugName.setLongClickable(true);

            lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            lp.addRule(RelativeLayout.CENTER_VERTICAL);

            // Ajout du label dans le conteneur gŽnŽral
            this.plug.addView(this.plugName, lp);

            // Bouton delete
            this.delete = new Button(parent);
            this.delete.setId(StepInterface.BUTTON_DELETE);
            this.delete.setBackgroundResource(R.drawable.ic_bt_del);
            this.delete.setClickable(true);
            this.delete.setOnClickListener(parent._controller);

            // Bouton Play
            this.actionText = new TextView(parent);
            this.actionText.setId(StepInterface.ACTION_TEXT);

            // Param�tres du layout pour le bouton Scenario
            lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
                    this.actionText.getId());

            // Ajout du bouton play au conteneur
            this.plug.addView(this.delete, lp);

            // Param�tres du layout pour le bouton reccurence
            lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            lp.addRule(RelativeLayout.CENTER_VERTICAL);
            lp.addRule(RelativeLayout.LEFT_OF, this.delete.getId());
            lp.rightMargin = 7;

            this.plug.addView(this.actionText, lp);

            this.addView(this.plug, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            this.setTexts(false);
            
            
            parent.registerForContextMenu(this);
        }
        
        /**
         * Permet de dŽfinir les textes des plugs et actions
         * Si param = true, on rafraichit les valeurs des champs
         * @param refresh
         */
        private void setTexts(boolean refresh) {
            Log.d("SAA::AI::refresh","START");
            this.plugName.setText("test");
//            this.actionText.setText(this.step.getAction() ?
//                    this.getContext().getString(
//                            R.string.add_scenario_plug_action_play) :
//                    this.getContext().getString(
//                            R.string.add_scenario_plug_action_stop));
//
//            if(refresh) {
//                this.plugName.postInvalidate();
//                this.actionText.postInvalidate();
//                
//            }

            Log.d("SAA::AI::refresh","END");
        }
    }

}